﻿using Inaction.Business.Security;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Inaction.UI
{
    public class FormLoader
    {
        static FormLoader loader;

        Form mainForm = null;
        private static FormLoader Loader
        {
            get
            {
                if (loader == null) loader = new FormLoader();
                return FormLoader.loader;
            }
        }

        private FormLoader() { }

        public static void SetMainForm(Form mainForm)
        {
            Loader.mainForm = mainForm;
        }

        private static Form CreateForm(MenuInfo menu)
        {
            var target = menu.TargetObj.Split(';');
            if (System.IO.File.Exists(target[0] + ".dll"))
            {
                target[0] += ".dll";
            }
            else if (System.IO.File.Exists(target[0] + ".exe"))
            {
                target[0] += ".exe";
            }
            else
            {
                throw new Exception("未找到此模块的文件,此模块可能仍在开发!");
            }
            var f = Inaction.Util.TypeHelper.LoadTypeInstance<Form>(target[0], target[1], target.Length > 2 ? target[3].Split(',') : null);
            f.Text = menu.Name;
            return f;
        }

        public static void InitForm(Form form)
        {
            form.IsMdiContainer = false;
            form.TopLevel = false;
            form.ShowIcon = false;
            form.ShowInTaskbar = false;
            form.TopMost = false;
            form.MdiParent = Loader.mainForm;
            form.Show();
        }

        public static void LoadForm(MenuInfo menu)
        {
            Form form = null;
            if (!loadedForms.ContainsKey(menu))
            {
                form = CreateForm(menu);
                form.Disposed += (sender, e) => { loadedForms.Remove(menu); };
                loadedForms.Add(menu, form);
                InitForm(form);
                return;
            }

            form = loadedForms[menu];
            if (form.IsDisposed)
            {
                var type = form.GetType();
                form = (Form)Activator.CreateInstance(type);
                InitForm(form);
            }
            form.Activate();
        }

        static Dictionary<MenuInfo, Form> loadedForms = new Dictionary<MenuInfo, Form>();
    }
}
